package com.shimao.celnet.payment.controller.apinotcheck;

import com.baiwang.bop.request.impl.invoice.common.InvoiceDetails;
import com.baiwang.bop.request.impl.invoice.common.InvoiceMainInfo;
import com.baiwang.bop.respose.entity.InvoiceOpenResponse;
import com.baiwang.bop.respose.entity.InvoiceQueryResponse;
import com.shimao.celnet.payment.model.PInvoiceBlue;
import com.shimao.celnet.payment.model.PInvoiceBlueDetail;
import com.shimao.celnet.payment.model.PInvoiceRed;
import com.shimao.celnet.payment.model.PInvoiceRedDetail;
import com.shimao.celnet.payment.service.PInvoiceBlueService;
import com.shimao.celnet.payment.service.PInvoiceRedService;
import com.shimao.celnet.payment.util.FinalUtil;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.List;
import java.util.Map;

/**
 * 2018/01/03
 * christ
 * 世茂支付平台 → 外部系统；   【数据】：开票结果信息；
 *  通过百望响应给我们的数据构建蓝票和红票信息以JSONObject返回给调用者
 */
@RestController
@Service
public class CallOut_invOpenRetInfoOutController {
    protected Logger logger = Logger.getLogger(this.getClass());
    @Autowired//开票申请
    private PInvoiceBlueService pInvoiceBlueService;

    @Autowired//开票申请
    private PInvoiceRedService pInvoiceRedService;

    public JSONObject invOpenRetBlueInfoOut(InvoiceQueryResponse response, PInvoiceBlue pInvoiceBlue, String invoiceUrl) {
        String guid = pInvoiceBlue.getGuid();
        Map<String, Object> blueRetMap = pInvoiceBlueService.getInfo(guid);
        JSONObject jsonObject = new JSONObject();
        JSONArray jsonArray = new JSONArray();
        List<InvoiceMainInfo> invoiceList = response.getInvoiceList();//百望响应给我们的数据
        for (InvoiceMainInfo invoiceMainInfo : invoiceList) {
            jsonObject.put("receiptGuid", guid);//记录guid（单位：分）
            jsonObject.put("blueRedType", FinalUtil.INVOICE_BULE);
            jsonObject.put("invoiceTypeCode", pInvoiceBlue.getInvoiceTypeCode());
            jsonObject.put("invoiceCode", invoiceMainInfo.getInvoiceCode());//发票代码（单位：分）
            jsonObject.put("invoiceNo", invoiceMainInfo.getInvoiceNo());//发票号码
            jsonObject.put("invoiceDate", invoiceMainInfo.getInvoiceDate());//开票日期
            jsonObject.put("taxControlCode", invoiceMainInfo.getTaxationMode());//税控码
            jsonObject.put("invoiceCheckCode", invoiceMainInfo.getInvoiceCheckCode());//校验码
            jsonObject.put("invoiceQrCode", invoiceMainInfo.getInvoiceQrCode());//二维码
            jsonObject.put("deductibleAmount", invoiceMainInfo.getDeductibleAmount());//扣除额
            jsonObject.put("invoiceTotalPrice", invoiceMainInfo.getInvoiceTotalPrice());//合计金额
            jsonObject.put("invoiceTotalTax", invoiceMainInfo.getInvoiceTotalTax());//合计税额
            jsonObject.put("invoiceTotalPriceTax", invoiceMainInfo.getInvoiceTotalPriceTax());//价税合计
            if (invoiceUrl != null) {
                jsonObject.put("invoiceUrl", invoiceUrl);//版式生成电子url
            }
            JSONObject json = new JSONObject();
                for (InvoiceDetails InvoiceDetailsList : invoiceMainInfo.getInvoiceDetailsList()) {
                    if ("0".equals(InvoiceDetailsList.getPriceTaxMark())) {  //PriceTaxMark 0：表示含稅
                        for (PInvoiceBlueDetail pInvoiceBlueDetail : (List<PInvoiceBlueDetail>) blueRetMap.get("pInvoiceDetailList")) {
                            if (pInvoiceBlueDetail.getGoodsLineNo().equals(InvoiceDetailsList.getGoodsLineNo())) {
                                json.put("exsysDetailID", pInvoiceBlueDetail.getExsysDetailId());//外部系统明细id
                            }
                        }
                        json.put("goodsLineNo", InvoiceDetailsList.getGoodsLineNo());//明细行号
                        json.put("goodsTotalPriceTax", String.valueOf(Float.valueOf(InvoiceDetailsList.getGoodsTotalPrice()) + Float.valueOf(InvoiceDetailsList.getGoodsTotalTax())));//价税金额（单位：分），开票时传入的金额
                        json.put("goodsTotalPrice", String.valueOf(Float.valueOf(InvoiceDetailsList.getGoodsTotalPrice())));//税金额（含税）（单位：分）
                        json.put("goodsTotalTax", InvoiceDetailsList.getGoodsTotalTax());//税额（单位：分）
                        json.put("goodsTaxRate", InvoiceDetailsList.getGoodsTaxRate());//税率
                        jsonArray.add(json);
                    }else {//PriceTaxMark 1：表示不含税
                        for (PInvoiceBlueDetail pInvoiceBlueDetail : (List<PInvoiceBlueDetail>) blueRetMap.get("pInvoiceDetailList")) {
                            if (pInvoiceBlueDetail.getGoodsLineNo().equals(InvoiceDetailsList.getGoodsLineNo())) {
                                json.put("exsysDetailID", pInvoiceBlueDetail.getExsysDetailId());//外部系统明细id
                            }
                        }
                        json.put("goodsLineNo", InvoiceDetailsList.getGoodsLineNo());//明细行号
                        json.put("goodsTotalPriceTax", InvoiceDetailsList.getGoodsTotalPrice());//价税金额（单位：分），开票时传入的金额
                        //todo 这里计算存在会有类似0.0000000000000002的误差   解决：比如12.11+1.10转成1211+110计算，最后再/100
                        json.put("goodsTotalPrice", String.valueOf((Float.valueOf(InvoiceDetailsList.getGoodsTotalPrice())*100 - Float.valueOf(InvoiceDetailsList.getGoodsTotalTax())*100)/100));//税金额（不含税）=价税金额 - 税额（单位：分）
                        json.put("goodsTotalTax", InvoiceDetailsList.getGoodsTotalTax());//税额（单位：分）
                        json.put("goodsTaxRate", InvoiceDetailsList.getGoodsTaxRate());//税率
                        jsonArray.add(json);
                    }
                }
            jsonObject.put("invoiceDetailsList", jsonArray);
        }
        return jsonObject;
    }

    public JSONObject invOpenRetRedInfoOut(InvoiceQueryResponse response, PInvoiceRed pInvoiceRed, String invoiceUrl) {
        String guid = pInvoiceRed.getGuid();
        Map<String, Object> RedRetMap = pInvoiceRedService.getInfo(guid);
        JSONObject jsonObject = new JSONObject();
        JSONArray jsonArray = new JSONArray();
        List<InvoiceMainInfo> invoiceList = response.getInvoiceList();
        for (InvoiceMainInfo invoiceMainInfo : invoiceList) {
            jsonObject.put("receiptGuid", guid);
            jsonObject.put("blueRedType", FinalUtil.INVOICE_RED);
            jsonObject.put("invoiceTypeCode", pInvoiceRed.getInvoiceTypeCode());
            jsonObject.put("invoiceCode", invoiceMainInfo.getInvoiceCode());//发票代码
            jsonObject.put("invoiceNo", invoiceMainInfo.getInvoiceNo());//发票号码
            jsonObject.put("invoiceDate", invoiceMainInfo.getInvoiceDate());//开票日期
            jsonObject.put("taxControlCode", invoiceMainInfo.getTaxationMode());//税控码
            jsonObject.put("invoiceCheckCode", invoiceMainInfo.getInvoiceCheckCode());//校验码
            jsonObject.put("invoiceQrCode", invoiceMainInfo.getInvoiceQrCode());//二维码
            jsonObject.put("deductibleAmount", invoiceMainInfo.getDeductibleAmount());//扣除额（单位：元）
            jsonObject.put("invoiceTotalPrice", invoiceMainInfo.getInvoiceTotalPrice());//价税合计
            jsonObject.put("invoiceTotalTax", invoiceMainInfo.getInvoiceTotalTax());//合计金额（单位：元）
            jsonObject.put("invoiceTotalPriceTax", invoiceMainInfo.getInvoiceTotalPriceTax());//合计税额（单位：元）
            if (invoiceUrl != null) {
                jsonObject.put("invoiceUrl", invoiceUrl);//版式生成电子url
            }
            JSONObject json = new JSONObject();
            for (InvoiceDetails InvoiceDetailsList : invoiceMainInfo.getInvoiceDetailsList()) {
                if ("0".equals(InvoiceDetailsList.getPriceTaxMark())) {//PriceTaxMark 0：表示含稅
                    for (PInvoiceRedDetail pInvoiceRedDetail : (List<PInvoiceRedDetail>) RedRetMap.get("pInvoiceDetailList")) {
                        if (pInvoiceRedDetail.getGoodsLineNo().equals(InvoiceDetailsList.getGoodsLineNo())) {
                            json.put("exsysDetailID", pInvoiceRedDetail.getExsysDetailId());//外部系统明细id
                        }
                    }
                    json.put("goodsLineNo", InvoiceDetailsList.getGoodsLineNo());//明细行号
                    json.put("goodsTotalPriceTax", Float.valueOf(InvoiceDetailsList.getGoodsTotalPrice()) + Float.valueOf(InvoiceDetailsList.getGoodsTotalTax()));//价税金额（单位：分），开票时传入的金额
                    json.put("goodsTotalPrice", InvoiceDetailsList.getGoodsTotalPrice());//税金额（不含税）=价税金额 - 税额（单位：元）
                    json.put("goodsTotalTax", InvoiceDetailsList.getGoodsTotalTax());//税额（单位：元）
                    json.put("goodsTaxRate", InvoiceDetailsList.getGoodsTaxRate());//税率
                    jsonArray.add(json);
                }else {//PriceTaxMark 1：表示不含税
                    for (PInvoiceRedDetail pInvoiceRedDetail : (List<PInvoiceRedDetail>) RedRetMap.get("pInvoiceDetailList")) {
                        if (pInvoiceRedDetail.getGoodsLineNo().equals(InvoiceDetailsList.getGoodsLineNo())) {
                            json.put("exsysDetailID", pInvoiceRedDetail.getExsysDetailId());//外部系统明细id
                        }
                    }
                    json.put("goodsLineNo", InvoiceDetailsList.getGoodsLineNo());//明细行号
                    json.put("goodsTotalPriceTax", InvoiceDetailsList.getGoodsTotalPrice());//价税金额（单位：分），开票时传入的金额
                    json.put("goodsTotalPrice", String.valueOf((Float.valueOf(InvoiceDetailsList.getGoodsTotalPrice())*100 - Float.valueOf(InvoiceDetailsList.getGoodsTotalTax())*100)/100));//税金额（不含税）=价税金额 - 税额（单位：元）
                    json.put("goodsTotalTax", InvoiceDetailsList.getGoodsTotalTax());//税额（单位：元）
                    json.put("goodsTaxRate", InvoiceDetailsList.getGoodsTaxRate());//税率
                    jsonArray.add(json);
                }
            }
            jsonObject.put("invoiceDetailsList", jsonArray);
        }
        return jsonObject;
    }
    /**
     * 当查询接口不能调用时，调用改方法
     */
    public JSONObject invOpenRetBlueInfoOut(InvoiceOpenResponse response, PInvoiceBlue pInvoiceBlue, String invoiceUrl) {
        String guid = pInvoiceBlue.getGuid();
        Map<String, Object> blueRetMap = pInvoiceBlueService.getInfo(guid);
        JSONObject jsonObject = new JSONObject();
        JSONArray jsonArray = new JSONArray();
        float invoiceTotalPriceSum = 0.0f; // 总价税合计
        float InvoiceTotalTaxSum = 0.0f; //总税额
        DecimalFormat fnum = new DecimalFormat("##0.00");
        //拼接返回json串
        jsonObject.put("receiptGuid", guid);//记录guid（单位：分）
        jsonObject.put("blueRedType", FinalUtil.INVOICE_BULE);
        jsonObject.put("invoiceTypeCode", pInvoiceBlue.getInvoiceTypeCode());
        jsonObject.put("invoiceCode", response.getInvoiceCode());
        jsonObject.put("invoiceNo", response.getInvoiceNo());//发票号码
        jsonObject.put("invoiceDate", response.getInvoiceDate());//开票日期
        jsonObject.put("taxControlCode", response.getTaxControlCode());//税控码
        jsonObject.put("invoiceCheckCode", response.getInvoiceCheckCode());//校验码
        jsonObject.put("invoiceQrCode", response.getInvoiceQrCode());//二维码
        jsonObject.put("deductibleAmount", pInvoiceBlue.getDeductibleAmount());//扣除额
        jsonObject.put("invoiceTotalPriceTax", fnum.format(Float.valueOf(pInvoiceBlue.getInvoiceTotalPriceTax())/100));//价税合计
        if (invoiceUrl != null) {
            jsonObject.put("invoiceUrl", invoiceUrl);//版式生成电子url
        }

        for (PInvoiceBlueDetail pInvoiceBlueDetail : (List<PInvoiceBlueDetail>) blueRetMap.get("pInvoiceDetailList")) {
            JSONObject json = new JSONObject();
            //价税合计
            float totalPriceTax = Float.valueOf(pInvoiceBlueDetail.getGoodsTotalPrice());
            //税额 = 价税合计 * 税率 / （1+税率）
            float totalTax = Float.valueOf(pInvoiceBlueDetail.getGoodsTotalPrice()) * Float.valueOf(pInvoiceBlueDetail.getGoodsTaxRate()) / (1 + Float.valueOf(pInvoiceBlueDetail.getGoodsTaxRate()));
            //金额（不含税）
            float totalPrice = totalPriceTax - totalTax;

            json.put("exsysDetailID", pInvoiceBlueDetail.getExsysDetailId());//外部系统明细idjson.put("goodsLineNo", InvoiceDetailsList.getGoodsLineNo());//明细行号
            json.put("goodsTotalPriceTax", fnum.format(totalPriceTax / 100));//价税金额（单位：分），开票时传入的金额
            json.put("goodsTotalPrice", fnum.format(totalPrice / 100));//税金额（不含税）=价税金额 - 税额（单位：元）
            json.put("goodsTotalTax", fnum.format(totalTax / 100));//税额（单位：元）
            json.put("goodsTaxRate", pInvoiceBlueDetail.getGoodsTaxRate());//税率
            jsonArray.add(json);
            invoiceTotalPriceSum = invoiceTotalPriceSum + totalPrice;
            InvoiceTotalTaxSum = InvoiceTotalTaxSum + totalTax;
        }
        jsonObject.put("invoiceTotalPrice", fnum.format(invoiceTotalPriceSum / 100));
        jsonObject.put("invoiceTotalTax", fnum.format(InvoiceTotalTaxSum / 100));
        jsonObject.put("invoiceDetailsList", jsonArray);
        return jsonObject;
    }

    public JSONObject invOpenRetBlueInfoOut(PInvoiceBlue pInvoiceBlue, String invoiceUrl) {
        String guid = pInvoiceBlue.getGuid();
        Map<String, Object> blueRetMap = pInvoiceBlueService.getInfo(guid);
        JSONObject jsonObject = new JSONObject();
        JSONArray jsonArray = new JSONArray();
        float invoiceTotalPriceSum = 0.0f; // 总价税合计
        float InvoiceTotalTaxSum = 0.0f; //总税额
        DecimalFormat fnum = new DecimalFormat("##0.00");
        //拼接返回json串
        jsonObject.put("receiptGuid", guid);//记录guid（单位：分）
        jsonObject.put("blueRedType", FinalUtil.INVOICE_BULE);
        jsonObject.put("invoiceTypeCode", pInvoiceBlue.getInvoiceTypeCode());
        jsonObject.put("invoiceCode", pInvoiceBlue.getInvoiceCode());
        jsonObject.put("invoiceNo", pInvoiceBlue.getInvoiceNo());//发票号码
        jsonObject.put("invoiceDate", pInvoiceBlue.getInvoiceEndTime());//开票日期
        jsonObject.put("taxControlCode", pInvoiceBlue.getTaxControlCode());//税控码
        jsonObject.put("invoiceCheckCode", pInvoiceBlue.getInvoiceCheckCode());//校验码
        jsonObject.put("invoiceQrCode", pInvoiceBlue.getInvoiceQrcode());//二维码
        jsonObject.put("deductibleAmount", pInvoiceBlue.getDeductibleAmount());//扣除额
        jsonObject.put("invoiceTotalPriceTax", fnum.format(Float.valueOf(pInvoiceBlue.getInvoiceTotalPriceTax())/100));//价税合计
        if (invoiceUrl != null) {
            jsonObject.put("invoiceUrl", invoiceUrl);//版式生成电子url
        }

        for (PInvoiceBlueDetail pInvoiceBlueDetail : (List<PInvoiceBlueDetail>) blueRetMap.get("pInvoiceDetailList")) {
            JSONObject json = new JSONObject();
            //价税合计
            float totalPriceTax = Float.valueOf(pInvoiceBlueDetail.getGoodsTotalPrice());
            //税额 = 价税合计 * 税率 / （1+税率）
            float totalTax = Float.valueOf(pInvoiceBlueDetail.getGoodsTotalPrice()) * Float.valueOf(pInvoiceBlueDetail.getGoodsTaxRate()) / (1 + Float.valueOf(pInvoiceBlueDetail.getGoodsTaxRate()));
            //金额（不含税）
            float totalPrice = totalPriceTax - totalTax;

            json.put("exsysDetailID", pInvoiceBlueDetail.getExsysDetailId());//外部系统明细idjson.put("goodsLineNo", InvoiceDetailsList.getGoodsLineNo());//明细行号
            json.put("goodsTotalPriceTax", fnum.format(totalPriceTax / 100));//价税金额（单位：分），开票时传入的金额
            json.put("goodsTotalPrice", fnum.format(totalPrice / 100));//税金额（不含税）=价税金额 - 税额（单位：元）
            json.put("goodsTotalTax", fnum.format(totalTax / 100));//税额（单位：元）
            json.put("goodsTaxRate", pInvoiceBlueDetail.getGoodsTaxRate());//税率
            jsonArray.add(json);
            invoiceTotalPriceSum = invoiceTotalPriceSum + totalPrice;
            InvoiceTotalTaxSum = InvoiceTotalTaxSum + totalTax;
        }
        jsonObject.put("invoiceTotalPrice", fnum.format(invoiceTotalPriceSum / 100));
        jsonObject.put("invoiceTotalTax", fnum.format(InvoiceTotalTaxSum / 100));
        jsonObject.put("invoiceDetailsList", jsonArray);
        return jsonObject;
    }

    /**
     * 当查询接口不能调用时，调用改方法
     */
    public JSONObject invOpenRetRedInfoOut1( PInvoiceRed pInvoiceRed,  String invoiceUrl) {
        String guid = pInvoiceRed.getGuid();
        Map<String, Object> RedRetMap = pInvoiceRedService.getInfo(guid);
        JSONObject jsonObject = new JSONObject();
        JSONArray jsonArray = new JSONArray();
        float invoiceTotalPriceSum = 0.0f; // 总价税合计
        float InvoiceTotalTaxSum = 0.0f; //总税额
        DecimalFormat fnum = new DecimalFormat("##0.00");
            jsonObject.put("receiptGuid", guid);
            jsonObject.put("blueRedType", FinalUtil.INVOICE_RED);
            jsonObject.put("invoiceTypeCode", pInvoiceRed.getInvoiceTypeCode());
            jsonObject.put("invoiceCode", pInvoiceRed.getInvoiceCode());//发票代码
            jsonObject.put("invoiceNo", pInvoiceRed.getInvoiceNo());//发票号码
            jsonObject.put("invoiceDate", pInvoiceRed.getInvoiceStartTime());//开票日期
            jsonObject.put("taxControlCode", pInvoiceRed.getTaxationMode());//税控码
            jsonObject.put("invoiceCheckCode", pInvoiceRed.getInvoiceCheckCode());//校验码
            jsonObject.put("invoiceQrCode", pInvoiceRed.getInvoiceQrcode());//二维码
            jsonObject.put("deductibleAmount", pInvoiceRed.getDeductibleAmount());//扣除额（单位：元）
            //jsonObject.put("invoiceTotalPrice", pInvoiceRed.getInvoiceTotalPrice());//价税合计
           // jsonObject.put("invoiceTotalTax", pInvoiceRed.getInvoiceTotalTax());//合计金额（单位：元）
            //jsonObject.put("invoiceTotalPriceTax", pInvoiceRed.getInvoiceTotalPriceTax());//合计税额（单位：元）
            if (invoiceUrl != null) {
                jsonObject.put("invoiceUrl", invoiceUrl);//版式生成电子url
            }
            JSONObject json = new JSONObject();
            for (PInvoiceRedDetail pInvoiceRedDetail : (List<PInvoiceRedDetail>) RedRetMap.get("pInvoiceDetailList")) {
                //价税合计
                float totalPriceTax = Float.valueOf(pInvoiceRedDetail.getGoodsTotalPrice());
                //税额 = 价税合计 * 税率 / （1+税率）
                float totalTax = Float.valueOf(pInvoiceRedDetail.getGoodsTotalPrice()) * Float.valueOf(pInvoiceRedDetail.getGoodsTaxRate()) / (1 + Float.valueOf(pInvoiceRedDetail.getGoodsTaxRate()));
                //金额（不含税）
                float totalPrice = totalPriceTax - totalTax;

                json.put("exsysDetailID", pInvoiceRedDetail.getExsysDetailId());//外部系统明细id
                invoiceTotalPriceSum = invoiceTotalPriceSum + totalPrice;
                InvoiceTotalTaxSum = InvoiceTotalTaxSum + totalTax;
                json.put("goodsLineNo", pInvoiceRedDetail.getGoodsLineNo());//明细行号
                json.put("goodsTotalPriceTax", fnum.format(-totalPriceTax / 100));//价税金额（单位：分），开票时传入的金额
                json.put("goodsTotalPrice", fnum.format(-totalPrice / 100));//税金额（不含税）=价税金额 - 税额（单位：元）
                json.put("goodsTotalTax", fnum.format(-totalTax / 100));//税额（单位：元）
                json.put("goodsTaxRate", pInvoiceRedDetail.getGoodsTaxRate());//税率
                jsonArray.add(json);

             }
            jsonObject.put("invoiceTotalPrice", fnum.format(-invoiceTotalPriceSum / 100));
            jsonObject.put("invoiceTotalTax", fnum.format(-InvoiceTotalTaxSum / 100));
            jsonObject.put("invoiceTotalPriceTax", fnum.format(-Float.valueOf(pInvoiceRed.getInvoiceTotalPriceTax())/100));
            jsonObject.put("invoiceDetailsList", jsonArray);

        return jsonObject;
    }
}